package com.hucii.app.db;

import java.lang.reflect.Field;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

	// 数据库版本
	public final static int DB_VERSION = 1;
	// 数据库名
	public final static String DB_NAME = "bookinfo.db";

	// 筛选历史

	private Context mContext;

	public DBHelper(Context context) {
		super(context, DB_NAME, null, DB_VERSION);
		this.mContext = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.beginTransaction();
		try {

			db.setTransactionSuccessful();

		} catch (Exception e) {

			e.printStackTrace();

		} finally {
			db.endTransaction();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.beginTransaction();
		try {
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
	}

	private String drop(Class c) {
		return "DROP TABLE IF EXISTS " + c.getSimpleName();
	}

	private String drop(String tableName) {
		return "DROP TABLE IF EXISTS " + tableName;
	}

	/**
	 * 创建表 obj 实体对象 实体中_id就是数据库的_id
	 */
	private <T> String createTable(Class<T> c) {
		return createTable(c, c.getSimpleName());
	}

	private <T> String createTable(Class<T> c, String tableName) {
		StringBuffer sBuffer = new StringBuffer();

		sBuffer.append("create table if not exists " + tableName + " " + "(_ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,");

		Field[] fields = c.getFields();
		// Field[] fields = obj.getClass().getDeclaredFields();
		for (Field field : fields) {
			if (!field.getName().equals("_id") && !"CREATOR".equals(field.getName()) && !"CONTENTS_FILE_DESCRIPTOR".equals(field.getName())
					&& !"PARCELABLE_WRITE_RETURN_VALUE".equals(field.getName()))
				// field.setAccessible(true);
				sBuffer.append(field.getName() + " TEXT,");
		}
		sBuffer.deleteCharAt(sBuffer.length() - 1);
		sBuffer.append(");");
		return sBuffer.toString();
	}

}
